package base.transporte;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public class UDPSocketSR {

	private DatagramSocket socketUDP;

	public UDPSocketSR(int port) throws SocketException {
		socketUDP = new DatagramSocket(port);
	}
	
	public UDPSocketSR() throws SocketException {
		socketUDP = new DatagramSocket();
	}

	public void setReceiveBufferSize(int size) throws SocketException{
		socketUDP.setReceiveBufferSize(size);
	}
	
	public void setSendBufferSize(int size) throws SocketException{
		socketUDP.setSendBufferSize(size);
	}
	
	public void setSoTimeout(int timeout) throws SocketException{
		socketUDP.setSoTimeout(timeout);
	}
	
	public void close(){
		socketUDP.close();
	}
	
	public int getLocalPort(){
		return socketUDP.getLocalPort();
	}
	
	public SRPacket receivePacket() throws IOException, SocketTimeoutException {
		SRPacket retorno = null;

		byte[] receiveData = new byte[Constantes.packetSizeMax];
		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

		this.socketUDP.receive(receivePacket);
		retorno = new SRPacket(receivePacket.getData());
		retorno.setSenderIp(receivePacket.getAddress());
		retorno.setSenderPort(receivePacket.getPort());
		retorno.setSocketAddress(receivePacket.getSocketAddress());

		return retorno;
	}

	public void sendPacket(SRPacket pkt, InetAddress ip, int port) throws IOException {
		byte[] sendData = pkt.getBytes();
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
		this.socketUDP.send(sendPacket);
	}

	
	public void sendAck(int seqNum, InetAddress ip, int port) throws Exception {
		SRPacket pkt = new SRPacket(seqNum, null);
		byte[] sendData = pkt.getBytes();
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
		this.socketUDP.send(sendPacket);
	}
	
}
